#!/bin/bash

# 快速修复前端服务启动问题
# 解决端口占用冲突

set -e

FRONTEND_PORT=7171
BACKEND_PORT=7172

echo "🔧 修复前端服务启动问题..."

# 拉取最新代码
echo "拉取最新代码..."
git pull  || {
    echo "⚠️  Git pull 失败，继续执行..."
}

# 测试并重新加载nginx配置
echo "测试并重新加载nginx配置..."
sudo nginx -t && sudo nginx -s reload || {
    echo "⚠️  Nginx配置重载失败，继续执行..."
}

# 停止所有 PM2 进程
echo "停止 PM2 进程..."
pm2 stop all 2>/dev/null || true
pm2 delete all 2>/dev/null || true

# 强制清理端口占用
echo "清理端口占用..."
sudo fuser -k $FRONTEND_PORT/tcp 2>/dev/null || true
sudo fuser -k $BACKEND_PORT/tcp 2>/dev/null || true
sleep 2

# 使用 lsof 彻底清理
if lsof -i:$FRONTEND_PORT > /dev/null 2>&1; then
    echo "强制清理端口 $FRONTEND_PORT..."
    sudo lsof -ti:$FRONTEND_PORT | xargs sudo kill -9 2>/dev/null || true
fi

if lsof -i:$BACKEND_PORT > /dev/null 2>&1; then
    echo "强制清理端口 $BACKEND_PORT..."
    sudo lsof -ti:$BACKEND_PORT | xargs sudo kill -9 2>/dev/null || true
fi

sleep 2

# 重新启动服务
echo "重新启动后端服务..."
cd backend
echo "安装后端依赖..."
pnpm install --prod || {
    echo "⚠️  后端依赖安装失败，继续执行..."
}

echo "� 重新生成Prisma客户端..."
npx prisma generate || {
    echo "❌ Prisma客户端生成失败！"
    exit 1
}

echo "🗄️ 运行数据库迁移..."
npx prisma migrate deploy || {
    echo "⚠️  数据库迁移失败，继续执行..."
}

echo "�🔨 构建后端代码（重要：包含聊天功能）..."
# 首先尝试生产构建脚本
if pnpm run build:prod; then
    echo "✅ 使用 build:prod 构建成功"
elif pnpm install --dev && pnpm run build; then
    echo "✅ 安装开发依赖后构建成功"
else
    echo "❌ 后端构建完全失败！"
    echo "� 尝试手动构建..."
    if [ -f "node_modules/.bin/tsc" ]; then
        ./node_modules/.bin/tsc -p tsconfig.build.json
        echo "✅ 使用 TypeScript 编译器构建成功"
    else
        echo "❌ 无法构建后端代码"
        exit 1
    fi
fi

echo "🚀 启动后端服务..."
PORT=$BACKEND_PORT pm2 start pnpm --name "ignitefun-backend" -- run start:prod

sleep 3

echo "重新启动前端服务..."
cd ../frontend
echo "安装前端依赖..."
pnpm install --prod || {
    echo "⚠️  前端依赖安装失败，继续执行..."
}
echo "🔨 构建前端项目..."
pnpm run build || {
    echo "❌ 前端构建失败！"
    exit 1
}
echo "🚀 启动前端服务..."
PORT=$FRONTEND_PORT pm2 start "pnpm run start -p $FRONTEND_PORT" --name "ignitefun-frontend" --env production

sleep 5

# 检查状态
echo "检查服务状态..."
pm2 list

echo ""
echo "检查端口状态:"
echo "后端端口 $BACKEND_PORT:"
lsof -i:$BACKEND_PORT || echo "端口未被监听"

echo "前端端口 $FRONTEND_PORT:"
lsof -i:$FRONTEND_PORT || echo "端口未被监听"

echo ""
echo "🧪 测试聊天功能..."
# 测试WebSocket连接
if command -v node &> /dev/null; then
    echo "测试WebSocket端点..."
    node -e "
    const https = require('https');
    const options = {
      hostname: 'localhost',
      port: $BACKEND_PORT,
      path: '/socket.io/?EIO=4&transport=polling',
      method: 'GET',
    };
    const req = https.request(options, (res) => {
      if (res.statusCode === 200) {
        console.log('✅ WebSocket端点响应正常');
      } else {
        console.log('❌ WebSocket端点响应异常:', res.statusCode);
      }
    });
    req.on('error', (err) => {
      console.log('❌ WebSocket端点测试失败:', err.message);
    });
    req.end();
    " 2>/dev/null || echo "⚠️  WebSocket测试失败"
fi

echo ""
echo "检查服务响应:"
if curl -s http://localhost:$BACKEND_PORT/api/health > /dev/null; then
    echo "✅ 后端服务正常"
else
    echo "❌ 后端服务异常"
fi

if curl -s http://localhost:$FRONTEND_PORT > /dev/null; then
    echo "✅ 前端服务正常"
else
    echo "❌ 前端服务异常"
    echo "查看前端日志:"
    pm2 logs ignitefun-frontend --lines 10
fi

echo ""
echo "🎉 修复完成！"
echo ""
echo "📋 部署总结："
echo "  - ✅ 代码已更新（git pull）"
echo "  - ✅ 后端已重新构建（包含聊天功能）"
echo "  - ✅ 前端已重新构建"
echo "  - ✅ 服务已重新启动"
echo ""
echo "🔍 验证步骤："
echo "  1. 访问: https://c4pad.fun"
echo "  2. 检查聊天室是否显示在线用户"
echo "  3. 尝试发送聊天消息"
echo ""
echo "📊 服务状态："
pm2 list
echo ""
echo "📝 查看日志命令："
echo "  - 后端日志: pm2 logs ignitefun-backend"
echo "  - 前端日志: pm2 logs ignitefun-frontend"
